package site.teamo.biu.net.client.core.http_https_proxy.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import site.teamo.biu.net.common.constant.ChannelAttributeKey;
import site.teamo.biu.net.common.handler.ExceptionHandler;
import site.teamo.biu.net.common.handler.SimpleTransferHandler;
import site.teamo.biu.net.common.http_https_proxy.ChannelGroups;
import site.teamo.biu.net.common.util.HostPort;
import site.teamo.biu.net.common.util.HttpUtils;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author haocongshun
 * @date 2023/06/08 14:33:12
 */
@Slf4j
public class DirectTransferClient {
    private final Bootstrap bootstrap;

    @Getter
    private final ChannelGroups channelGroups;

    private final EventLoopGroup group;

    //入流量统计
    private final AtomicLong in;

    //出流量统计
    private final AtomicLong out;

    public DirectTransferClient(AtomicLong in, AtomicLong out) {
        this.in = in;
        this.out = out;
        this.group = new NioEventLoopGroup();
        this.bootstrap = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new Initializer());
        this.channelGroups = new ChannelGroups();

    }

    public void http(HostPort hostPort, Channel channelFromBrowser, HttpRequest request) {
        Channel channelToDestination = establishConnection(hostPort, channelFromBrowser);
        channelFromBrowser.pipeline().remove("http-decoder");
        channelFromBrowser.pipeline().remove("http-encoder");
        channelFromBrowser.pipeline().addBefore("exception", "simple-transfer", new SimpleTransferHandler("将浏览器请求转发给目的地", out));
        //通道建立以后，需要把当前这一条http请求数据转发到服务端去
        //要将http的数据转换成首先将接受的请求转换成原始字节数据
        Object msg = HttpUtils.convertHttpRequestToOriginalMsg(request);
        channelToDestination.writeAndFlush(msg);
    }

    public void https(HostPort hostPort, Channel channelFromBrowser) {
        establishConnection(hostPort, channelFromBrowser);
        //向浏览器答复准备完成
        channelFromBrowser.writeAndFlush(HttpUtils.okResponse())
                .addListener(future -> {
                    //向浏览器答复成功后，接受浏览器请求时的编码和解码器
                    if (future.isSuccess()) {
                        channelFromBrowser.pipeline().remove("http-decoder");
                        channelFromBrowser.pipeline().remove("http-encoder");
                        channelFromBrowser.pipeline().addBefore("exception", "simple-transfer", new SimpleTransferHandler("将浏览器请求转发给目的地", out));
                    }
                });
    }

    public void close() {
        this.group.shutdownGracefully();
        this.channelGroups.close();
    }

    private Channel establishConnection(HostPort hostPort, Channel channelFromBrowser) {
        try {
            Channel channelToDestination = this.bootstrap.connect(hostPort.host(), hostPort.port()).sync().channel();
            channelFromBrowser.attr(ChannelAttributeKey.TARGET_CHANNEL).setIfAbsent(channelToDestination);
            channelToDestination.attr(ChannelAttributeKey.TARGET_CHANNEL).setIfAbsent(channelFromBrowser);
            channelGroups.put(hostPort, channelFromBrowser);
            channelFromBrowser.config().setAutoRead(true);
            return channelToDestination;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private class Initializer extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline()
                    .addLast("simple-transfer", new SimpleTransferHandler("将目的地响应转发给浏览器", in))
                    .addLast("idle", new IdleStateHandler(0, 0, 90, TimeUnit.SECONDS))
                    .addLast("exception", new ExceptionHandler());
        }
    }

}
